/**
 * 打包脚本 - 生成项目安装包
 * 用途：排除 node_modules 等不必要文件，打包成 .exe 安装程序
 */

const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const { execSync } = require('child_process');

const PROJECT_ROOT = path.join(__dirname, '..');
const OUTPUT_DIR = path.join(__dirname, 'dist');
const ARCHIVE_PATH = path.join(OUTPUT_DIR, 'elm-project.zip');

// 排除的目录和文件
const EXCLUDE_PATTERNS = [
  'node_modules',
  '.git',
  '.idea',
  'target',
  'dist',
  '.DS_Store',
  '*.log',
  '.env.local',
  '.env.*.local'
];

/**
 * 检查是否应该排除文件
 */
function shouldExclude(filePath, relativePath) {
  return EXCLUDE_PATTERNS.some(pattern => {
    if (pattern.includes('*')) {
      const regex = new RegExp(pattern.replace(/\*/g, '.*'));
      return regex.test(relativePath);
    }
    return relativePath.includes(pattern);
  });
}

/**
 * 递归添加文件到压缩包
 */
function addFilesToArchive(archive, dir, arcDir = '') {
  const files = fs.readdirSync(dir);

  files.forEach(file => {
    const filePath = path.join(dir, file);
    const relativePath = path.join(arcDir, file);

    if (shouldExclude(filePath, relativePath)) {
      console.log(`⊘ 跳过: ${relativePath}`);
      return;
    }

    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      addFilesToArchive(archive, filePath, relativePath);
    } else {
      archive.file(filePath, { name: relativePath });
      console.log(`✓ 添加: ${relativePath}`);
    }
  });
}

/**
 * 主打包函数
 */
async function buildInstaller() {
  console.log('🔨 开始构建安装包...\n');

  // 创建输出目录
  if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  }

  // 创建压缩包
  const output = fs.createWriteStream(ARCHIVE_PATH);
  const archive = archiver('zip', { zlib: { level: 9 } });

  return new Promise((resolve, reject) => {
    output.on('close', () => {
      console.log(`\n✅ 压缩包创建成功: ${ARCHIVE_PATH}`);
      console.log(`📦 压缩包大小: ${(archive.pointer() / 1024 / 1024).toFixed(2)} MB\n`);
      
      // 后续步骤
      console.log('📝 后续步骤:');
      console.log('1. 使用 NSIS 或 Inno Setup 将压缩包转换为 .exe 安装程序');
      console.log('2. 或使用 electron-builder 打包启动程序\n');
      
      resolve();
    });

    archive.on('error', reject);
    output.on('error', reject);

    archive.pipe(output);

    console.log('📂 正在扫描项目文件...\n');
    addFilesToArchive(archive, PROJECT_ROOT);

    // 添加启动脚本
    console.log('\n📄 添加启动脚本...');
    const startScriptPath = path.join(__dirname, 'start.js');
    if (fs.existsSync(startScriptPath)) {
      archive.file(startScriptPath, { name: 'start.js' });
      console.log('✓ 添加: start.js');
    }

    const configPath = path.join(__dirname, 'config.json');
    if (fs.existsSync(configPath)) {
      archive.file(configPath, { name: 'config.json' });
      console.log('✓ 添加: config.json');
    }

    archive.finalize();
  });
}

// 执行打包
buildInstaller().catch(err => {
  console.error('❌ 打包失败:', err);
  process.exit(1);
});
